using System.CodeDom.Compiler;
using System.Collections.Generic;

namespace MvvmOrm.Services
{
    public static class CodeCompiler
    {
        public static CompilerResults CompileCode(
            string[] sources, IEnumerable<string> refs, string outputAssembly, string xmlDocFilename)
        {
            CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
            CompilerParameters compilerParams = new CompilerParameters();

            compilerParams.GenerateExecutable = false;
            compilerParams.GenerateInMemory = false;
            compilerParams.IncludeDebugInformation = false;
            compilerParams.CompilerOptions += "/o+ ";
            compilerParams.WarningLevel = 0;
            compilerParams.OutputAssembly = outputAssembly;
            if (!string.IsNullOrWhiteSpace(xmlDocFilename))
                compilerParams.CompilerOptions += "/doc:\"" + xmlDocFilename + "\" ";

            compilerParams.ReferencedAssemblies.Add("System.dll");
            compilerParams.ReferencedAssemblies.Add("System.Core.dll");
            compilerParams.ReferencedAssemblies.Add("System.Data.dll");
            compilerParams.ReferencedAssemblies.Add("System.Xml.dll");
            if (refs != null)
                foreach (string refAssembly in refs)
                    compilerParams.ReferencedAssemblies.Add(refAssembly);

            return codeProvider.CompileAssemblyFromSource(compilerParams, sources);
        }
    }
}
